<?php
/**
 * Created by PhpStorm.
 * Script Name: BotSetting.php
 * Create: 2022/12/22 14:31
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */
namespace plugin\wechat\app\service;
use plugin\wechat\app\model\BotSetting as SettingM;

class BotSetting
{
    /**
     * 获取群发间隔时间
     * @param $company_id
     * @return int
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getStepTime($company_id = 0){
        $config_save = self::getSettings($company_id, 'save');
        if(empty($config_save['step_time'])){
            $arr = [1, 4];
        } else{
            $arr = explode('-', $config_save['step_time']);
        }
        return sleep(rand($arr[0], $arr[1]));
    }

    /**
     * 获取配置
     * @param int $company_id
     * @param null $name
     * @param bool $refresh
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException Author: fudaoji<fdj@kuryun.cn>
     */
    public static function getSettings($company_id = 0, $name = null,$refresh = false){
        $cache_key = wechat_cache_key('bot:'.$company_id.':' . (is_null($name) ? 'all' : $name));

        $list = cache($cache_key);
        if(empty($list) || $refresh){
            $list = SettingM::where('company_id', $company_id)
                ->column('value', 'name');
            foreach ($list as $k => &$v){
                $v = json_decode($v, true);
            }
        }
        cache($cache_key, $list);
        return isset($list[$name]) ? $list[$name] : $list;
    }
}